package com.xteam.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.tangkf.utils.CommonUtils;
import com.tangkf.utils.SysClassLoader;
import com.tangkf.utils.bean.ReqHelper;
import com.tangkf.utils.file.FileUtils;
import com.tangkf.utils.fileupload.FileUploadUtils;
import com.xteam.web.controller.upload.IUploadProcess;

public class FileUploadController extends MultiActionController {
	
	static final Logger	log				= Logger.getLogger(FileUploadController.class);

	String				resourcePath	= "";

	String				fileTypes		= "xlsx|xls|png|jpg|gif";
	long				maxFileSize		= 256000000;
	String				savePath		= "d:/files";
	String				procPackage		= "cn.mystic.web.former.fileupload.";

	public FileUploadController() {

	}

	/**
	 * 文件下载
	 * @author tangkf ---2012-2-12
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String file = request.getParameter("file");
		String rfile = request.getParameter("realName");
		response.setHeader("content-disposition", "attachment;filename=" + (rfile != null ? rfile : file));
		response.setContentType("text/html; charset=GBK");// 此项内容随文件类型而异 application/vnd.ms-excel

		if (file != null) {
			OutputStream os = null;
			FileInputStream fis = null;
			try {
				file = resourcePath + "/" + file;
				if (!(new File(file)).exists()) {
					log.error("没有文件");
					return null;
				}
				os = response.getOutputStream();
				byte temp[] = new byte[1000];
				fis = new FileInputStream(file);
				int n = 0;
				while ((n = fis.read(temp)) != -1) {
					os.write(temp, 0, n);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (os != null) os.close();
				if (fis != null) fis.close();
			}
		}
		return null;
	}

	/**
	 * 上传文件处理方法
	 * @author tangkf ---2012-3-3
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView upload(HttpServletRequest request, HttpServletResponse response) throws Exception {

		FileUploadUtils fuu = new FileUploadUtils(request, fileTypes, maxFileSize);

		String process = ReqHelper.getRequestString(request, "processClass");
		String isSave = ReqHelper.getRequestString(request, "isSave");

		// 设置进度监听器
		fuu.setProgressListerner(new ProgressListener() {
			public void update(long byteRead, long byteLength, int items) {
				log.info(byteRead + "-" + byteLength + "-" + items);
			}
		});

		// 多文件处理
		List<FileItem> fis = fuu.getFileItems();
		if (fis != null && fis.size() > 0) {
			for (FileItem fi : fis) {
				try {
					// 相对路径
					String filePath = this.makeFilePath(fi);
					// 绝对路径
					String realPath = savePath + "/" + filePath;
					// 保存文件
					if (!"false".equals(isSave)) fuu.saveFile(fi, realPath);

					// 定义默认返回信息
					String rinfo = "{'imgPath':'" + filePath + "','imgName':'" + fi.getName() + "',realPath:'" + realPath + "'}";

					// 给其他接口进行处理
					if (CommonUtils.notEmpty(process)) {
						Object procer = SysClassLoader.newObjectByName(procPackage + process);
						if (procer != null && procer instanceof IUploadProcess) {
							IUploadProcess fup = (IUploadProcess) procer;
							String tmp = fup.process(request,response,fuu,fi, filePath, realPath);
							if (tmp != null) rinfo = tmp;
						}
					}

					PrintWriter out = response.getWriter();
					out.print(rinfo);
					out.close();
				} catch (Exception e) {
					log.error("文件上传处理失败：" + e.getLocalizedMessage());
				}
			}
		}
		fuu.clear();
		return null;
	}

	/**
	 * 创建绝对路径，并返回相对路径
	 * @author tangkf ---2012-2-12
	 * @param fi
	 * @return
	 */
	public String makeFilePath(FileItem fi) {
		// 生成相对路径
		String xdpath = CommonUtils.getDateTime(new Date(), "yyyy") + "/" + CommonUtils.getDateTime(new Date(), "MM");

		// 文件绝对路径
		String realPath = savePath + "/" + xdpath;

		// 创建路径
		File dir = new File(realPath);
		FileUtils.makeDir(dir);

		// 扩展名
		String extName = fi.getName();
		extName = extName.substring(extName.lastIndexOf(".") + 1);

		// 生成文件名
		String fileName = CommonUtils.getRandomId() + "." + extName;

		return xdpath + "/" + fileName;
	}

	/**
	 * @param fileTypes 属性fileTypes.
	 */
	public void setFileTypes(String fileTypes) {
		this.fileTypes = fileTypes;
	}

	/**
	 * @param maxFileSize 属性maxFileSize.
	 */
	public void setMaxFileSize(long maxFileSize) {
		this.maxFileSize = maxFileSize;
	}

	/**
	 * @param savePath 属性savePath.
	 */
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	/**
	 * @param procPackage 属性procPackage.
	 */
	public void setProcPackage(String procPackage) {
		this.procPackage = procPackage;
	}

	/**
	 * @param resourcePath 属性resourcePath.
	 */
	public void setResourcePath(String resourcePath) {
		this.resourcePath = resourcePath;
	}

}